package main

import (
	"html/template"
	"log"
	"os"
	"time"
)

func main() {
	test1()
	test2()
}

func test1() {
	const context = `<p>A: {{.A}}</p><p>B: {{.B}}</p>`

	t := template.Must(template.New("escape").Parse(context))

	var data struct {
		A string        // untrusted plain text
		B template.HTML // trusted HTML
	}
	data.A = "<b>Hello!</b>" // 被转义
	data.B = "<b>Hello!</b>" //正常显示HTML

	if err := t.Execute(os.Stdout, data); err != nil {
		log.Fatal(err)
	}

}

func test2() {
	const templ = `{{.TotalCount}} issues:
{{range .Items}}----------------------------------------
Number: {{.Number}}
User:   {{.User}}
Title:  {{.Title | printf "%.64s"}}
Age:    {{.CreatedAt | daysAgo}} days
{{end}}`

	type Item struct {
		Number    int
		User      string
		Title     string
		CreatedAt time.Time
	}

	type data struct {
		TotalCount int
		Items      []Item
	}

	d := data{
		TotalCount: 100,
		Items: []Item{
			Item{Number: 1, User: "张三", Title: "标题1", CreatedAt: time.Now()},
			Item{Number: 2, User: "李四", Title: "标题2", CreatedAt: time.Date(2023, 12, 4, 0, 0, 0, 0, time.Local)},
		},
	}

	t := template.Must(template.New("report").
		Funcs(template.FuncMap{"daysAgo": daysAgo}).
		Parse(templ))
	if err := t.Execute(os.Stdout, d); err != nil {
		log.Fatal(err)
	}
}

func daysAgo(t time.Time) int {
	return int(time.Since(t).Hours() / 24)
}
